package com.sudo.service.impl;

import com.sudo.common.enums.UserParams;
import com.sudo.common.utils.JsonUtils;
import com.sudo.common.utils.RedisOperator;
import com.sudo.common.utils.SysInfoUtils;
import com.sudo.mapper.my.SysMemLogMapper;
import com.sudo.pojo.SysMemLog;
import com.sudo.service.BaseService;
import com.sudo.service.SysMemLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author：为道日损 2020-07-03 14:47
 * webSite：https://www.sudo.ren
 */
@Service
public class SysMemLogServiceImpl extends BaseService implements SysMemLogService {

    @Autowired
    private SysMemLogMapper sysMemLogMapper;

    @Autowired
    private RedisOperator redisOperator;

    @Override
    public void insertMemLogToRedis() {
        SysMemLog sysMemLog = SysInfoUtils.dynamicMem();
        redisOperator.lpush(UserParams.REDIS_SYS_INFO.value+":"+UserParams.MEM.value,
                JsonUtils.objectToJson(sysMemLog));
    }

    @Override
    public void insertMemLogFromRedisToMysql() {
        List<SysMemLog> sysMemLogList = new ArrayList<>();
        for (int i = 0; i < 60; i++) {
            String jsonData = redisOperator.rpop(UserParams.REDIS_SYS_INFO.value+":"+UserParams.MEM.value);
            SysMemLog sysMemLog = JsonUtils.jsonToPojo(jsonData, SysMemLog.class);
            sysMemLogList.add(sysMemLog);
        }
        if (!CollectionUtils.isEmpty(sysMemLogList)){
            sysMemLogMapper.insertList(sysMemLogList);
        }
    }

    @Override
    public List<SysMemLog> getMemLogListFromRedis(Integer num) {
        List<SysMemLog> sysMemLogList = new ArrayList<>();
        List<String> memLogArr = redisOperator.lrange(UserParams.REDIS_SYS_INFO.value + ":" + UserParams.MEM.value, 0, num);
        for (String s : memLogArr) {
            SysMemLog sysCpuLog = JsonUtils.jsonToPojo(s, SysMemLog.class);
            sysMemLogList.add(sysCpuLog);
        }
        Collections.reverse(sysMemLogList);
        return sysMemLogList;
    }


}
